package java8Test.function.lambda.part2;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleDateFormatDemoTest4 {

    private static ThreadLocal<DateFormat> threadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        //1、创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(9);
        //2、为线程池分配任务
        ThreadPoolSafeTest threadPoolSafeTest = new ThreadPoolSafeTest();
        for (int i = 0; i < 9; i++) {
            pool.submit(threadPoolSafeTest);
        }
//        ThreadPoolUnSafeTest threadPoolUnSafeTest = new ThreadPoolUnSafeTest();
//        for (int i = 0; i < 9; i++) {
//            pool.submit(threadPoolUnSafeTest);
//        }
        //3、关闭线程池
        pool.shutdown();
    }

    static class ThreadPoolSafeTest implements Runnable {

        @Override
        public void run() {
            try {
                String dateString = threadLocal.get().format(new Date());
                Date parseDate = threadLocal.get().parse(dateString);
                String dateString2 = threadLocal.get().format(parseDate);
                System.out.println(Thread.currentThread().getName() + " date: " + threadLocal.get() + " 线程是否安全: " + dateString.equals(dateString2));
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName() + " 格式化失败 ");
            } finally {
                //避免内存泄漏，使用完threadLocal后要调用remove方法清除数据
                threadLocal.remove();
            }
        }
    }

    static class ThreadPoolUnSafeTest implements Runnable {

        @Override
        public void run() {
            try {
                String dateString = dateFormat.format(new Date());
                Date parseDate = dateFormat.parse(dateString);
                String dateString2 = dateFormat.format(parseDate);
                System.out.println(Thread.currentThread().getName() + " date: " + dateFormat + " 线程是否安全: " + dateString.equals(dateString2));
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName() + " 格式化失败 ");
            }
        }
    }
}

